Maximum product subarray¶
Time: O(N); Space: O(1); medium
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: A = [2,3,-2,4]
Output: 6
Explanation:
[2,3] has the largest product 6.
Example 2:
Input: A = [-2,0,-1]
Output: 0
Explanation:
The result cannot be 2, because [-2,-1] is not a subarray.
[1]:
class Solution1(object):
"""
Time: O(N)
Space: O(1)
"""
def maxProduct(self, A):
"""
:type A: List[int]
:rtype: int
"""
global_max, local_max, local_min = float("-inf"), 1, 1
for x in A:
local_max, local_min = max(x, local_max * x, local_min * x), min(x, local_max * x, local_min * x)
global_max = max(global_max, local_max)
return global_max
[2]:
s = Solution1()
A = [2,3,-2,4]
assert s.maxProduct(A) == 6
A = [-2,0,-1]
assert s.maxProduct(A) == 0
[3]:
class Solution2(object):
def maxProduct(self, A):
"""
:type A: List[int]
:rtype: int
"""
global_max, local_max, local_min = float("-inf"), 1, 1
for x in A:
local_max = max(1, local_max)
if x > 0:
local_max, local_min = local_max * x, local_min * x
else:
local_max, local_min = local_min * x, local_max * x
global_max = max(global_max, local_max)
return global_max
[4]:
s = Solution2()
A = [2,3,-2,4]
assert s.maxProduct(A) == 6
A = [-2,0,-1]
assert s.maxProduct(A) == 0
See also:¶
https://leetcode.com/problems/maximum-product-subarray
https://www.lintcode.com/problem/maximum-product-subarray/description
Related problems:¶
https://leetcode.com/problems/maximum-subarray/
https://leetcode.com/problems/house-robber/
https://leetcode.com/problems/product-of-array-except-self/
https://leetcode.com/problems/maximum-product-of-three-numbers/
https://leetcode.com/problems/subarray-product-less-than-k/
https://www.lintcode.com/problem/maximum-subarray-ii
https://www.lintcode.com/problem/minimum-subarray
https://www.lintcode.com/problem/maximum-subarray-difference
https://www.lintcode.com/problem/best-time-to-buy-and-sell-stock